<template>
	<view class="home page_old_diy flex-column tabbar-page-bottom" :style="homeStyle">
		<qh-navbar :title="totalData.page.title || store_name" :bgColor="totalData.page.topBackgroundColor || '#FFFFFF'"
			:color="totalData.page.topForeground == 1 ? '#ffffff' : '#000000'">
		</qh-navbar>
		<diy-home-top v-if="homeTopData" :componentData="homeTopData.data" :storeList="storeList" :index="store_index" :storeSwitch="store_switch"
			@add-to-car="toAddToCar" @get-sku="getSku">
		</diy-home-top>
		<diy-service v-for="(item, index) in diyServiceList" :key="index" :componentData="item.data" :storeInfo="storeList[store_index]"></diy-service>
		<view class="old-diy-content flex-column-100">
			<qh-scroll-view parent-el-name=".old-diy-content" @init="initScroll" :lowerEnabled="false" refresher-enabled
				@refresherrefresh="onPagePullDownRefresh" :refresher-triggered="isRefresh">
				<view v-for="(component, index) in totalData.components" :key="index">
					<diy-text v-if="component.sign == 'diy-text'" :componentData="component.data"></diy-text>
					<diy-banner v-else-if="component.sign == 'diy-banner'" :componentData="component.data"></diy-banner>
					<diy-nav v-else-if="component.sign == 'diy-nav'" :componentData="component.data"></diy-nav>
					<diy-seckill v-else-if="component.sign == 'diy-seckill'" :componentData="component.data" :store-id="store_id"></diy-seckill>
					<diy-group-buy v-else-if="component.sign == 'diy-group-buy'" :componentData="component.data" :store-id="store_id">
					</diy-group-buy>
					<diy-gift-card v-else-if="component.sign == 'diy-gift-card'" :componentData="component.data">
					</diy-gift-card>
					<diy-pre-sale v-else-if="component.sign == 'diy-pre-sale'" :componentData="component.data" :store-id="store_id">
					</diy-pre-sale>
					<diy-promotion v-else-if="component.sign == 'diy-promotion'" :componentData="component.data">
					</diy-promotion>
					<diy-goods v-else-if="component.sign == 'diy-goods'" :componentData="component.data" @add-to-car="toAddToCar" @get-sku="getSku"></diy-goods>
					<diy-magic-box v-else-if="component.sign == 'diy-magic-box'" :componentData="component.data">
					</diy-magic-box>
					<diy-service v-else-if="component.sign == 'diy-service'" :componentData="component.data" :storeInfo="storeList[store_index]"></diy-service>
					<template v-else-if="component.sign == 'diy-coupon'">
						<diy-coupon v-if="component.data.type == 1" :componentData="component.data" :city-code="cityCode"></diy-coupon>
						<template v-else-if="component.data.type == 4">
							<!-- #ifdef MP-ALIPAY -->
							<diy-coupon :componentData="component.data" :city-code="cityCode"></diy-coupon>
							<!-- #endif -->
						</template>
						<template v-else>
							<!-- #ifdef MP-WEIXIN -->
							<diy-coupon :componentData="component.data" :service_status="service_status" :ordinary_status="ordinary_status"></diy-coupon>
							<!-- #endif -->
						</template>
					</template>
					<template v-else-if="component.sign == 'diy-live'">
						<!-- #ifdef MP-WEIXIN -->
						<diy-live :componentData="component.data"></diy-live>
						<!-- #endif -->
					</template>
					<diy-gap v-else-if="component.sign == 'diy-gap'" :componentData="component.data"></diy-gap>
				</view>
			</qh-scroll-view>
		</view>

		<block v-if="showSelectSku">
			<choose-sku :sku="sku" :goodsinfo="goods" @close="closeSku"></choose-sku>
		</block>

		<view class="container" v-if='reward'>
			<view class='box'>
				<image :src='rewardBg' class='reward-bg'></image>
				<view @click='toOpen' class="reward-open" :class="{'reward-rotate': rotate}">
					<image v-if='rotate' mode="aspectFit" :src='open1Image'></image>
					<image v-else mode="aspectFit" :src='openImage'></image>
				</view>
				<view class='reward-money' v-if='open'>
					<text>￥</text>
					<text>{{money}}</text>
				</view>
				<view class='reward-tip' v-if='!open'>恭喜发财，大吉大利！</view>
				<view class='reward-tip' v-else>已放入会员卡余额</view>
				<view @click='closeReward' class='reward-close'>
					<icon type='cancel' size='30' color='#ffffff'></icon>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var app = getApp().globalData;
	import qhScrollMixin from "@/components/qh-scroll-view/mixins.js";
	export default {
		mixins: [qhScrollMixin], // 使用mixin
		data() {
			return {
				totalData: {},
				plugState: {},
				componentNames: {
					'diy-text': '标题文本',
					'diy-home-top': '顶部导航',
					'diy-banner': '轮播图片',
					'diy-nav': '图文导航',
					'diy-seckill': '秒杀',
					'diy-group-buy': '团购',
					'diy-gift-card': '礼品卡',
					'diy-promotion': '促销',
					'diy-goods': '商品',
					'diy-magic-box': '魔方',
					// 'diy-service': '在线客服',
					'diy-service': '悬浮按钮',
					'diy-pre-sale': '预售',
					'diy-coupon': '优惠券',
					'diy-live': '直播',
					'diy-gap': '间隔槽',
				},
				activeIndex: null,
				store_id: 0,
				store_index: 0,
				systemInfo: uni.getSystemInfoSync(),
				userInfo: {},
				storeList: [],
				store_switch: "", //门店能否切换 1 切换 2不能切换
				sku: {
					skuImg: '', //规格弹框图片
					skuName: '', //规格名称
					skuSelectIndex: [], //已选规格下标列表
					isSku: true, //是否是规格商品，针对扫码购
					shoppingNum: 1, //选择规格或扫码购商品详情时的加入购物车的数量
					canChangeCarNum: 1, //是否可以修改规格弹框数量
					user_type: 1, //用户类型  1普通  2plus  3常规会员
					skuPrice: '', //商品规格价
					skuNum: '', //商品规格库存
					skuShopMemStatus: 2, //规格商品是否开启普通会员价  1开启  2关闭
					skuShopMemPrice: '', //规格商品普通会员价
					skuPlusMemStatus: 2, //规格商品是否开启PLUS会员价  1开启  2关闭
					skuPlusPrice: '', //规格商品PLUS会员价
					sku_promotion_status: 0, //规格商品是否开启促销
					promotion_price: 0, //规格商品促销价
					canChangeAddNum: true, //是否可以增加
					goods_num: 0,
					showChangeNum: true, //是否显示选择数量
					btnText: '加入购物车', //按钮文字
				},
				goods: {},
				showSelectSku: false,
				open: false, // 红包是否被打开
				rotate: false, // 
				isVip: 0,
				reward: false,
				rewardBg: 'https://safood.supplyocta.com/Public/MallSmallApp/reward-bg.png',
				open1Image: 'https://safood.supplyocta.com/Public/MallSmallApp/open-1.png',
				openImage: 'https://www.xzthealth.com/Public/MallSmallApp/open.png',
				money: 0,
				isMerchantDiy: false, //是否为商户DIY
				service_status: '', //商家券  1已获取到服务商下的openid 2未获取到
				ordinary_status: '',
				store_name: '',
				user_type: '', //用户类型  1普通  2plus  3常规会员
				//#ifdef MP-ALIPAY
				cityCode: '', //用户城市编码
				//#endif
				isRefresh: false,
				homeTopData: null,
				diyServiceList: [],
				oldDiyData: {},
			}
		},
		computed: {
			homeStyle() {
				let css = {};
				if (this.totalData.page) {
					css['background-color'] = this.totalData.page.backgroundColor;
				}
				return this.$joinStyle(css);
			},
		},
		async mounted() {
			await this.$onLaunched;

			let storeInfo = uni.getStorageSync('storeInfo')

			if (storeInfo) {
				this.store_id = storeInfo.store_id;
			}
			app.resetStoreId();
			this.getBasicData();
			// #ifdef MP-WEIXIN
			this.getServicePermissions()
			// #endif
		},
		methods: {
			onShows() {
				let storeInfo = uni.getStorageSync('storeInfo')

				if (storeInfo) {
					this.store_id = storeInfo.store_id;
				}
				app.resetStoreId();
				this.getBasicData();
				// #ifdef MP-WEIXIN
				this.getServicePermissions()
				// #endif
			},
			async onPagePullDownRefresh() {
				this.isRefresh = true;
				await this.getOldPageData();
				await this.getBasicData(true);
				setTimeout(() => {
					this.isRefresh = false;
					uni.showToast({
						title: '刷新成功',
						duration: 800
					})
				}, 1000)
			},
			getOldPageData() {
				return new Promise(async resolve => {
					try {
						const {
							diy_status,
							status,
							data,
							plug_state,
							store_merchant,
							message
						} = await this.$request('/SmallProgramApi/Diy/getStoreDiy_v1');
						if (status == 1 && diy_status == 1) {
							this.oldDiyData = {
								totalData: data,
								plugState: plug_state,
								isMerchantDiy: store_merchant == 2 ? true : false,
							};
							this.$nextTick(() => {
								resolve(true);
							})
						} else {
							resolve(false);
						}
					} catch (err) {
						console.error('getOldPageData', err)
						resolve(false);
					}
				})
			},
			async getBasicData(bool = false) {
				if (!this.storeList.length || this.storeList[0].store_id != this.$store.store_id) {
					this.totalData = {};
					await this.getStore();
				}
				if (!this.storeList.length) return;

				if (this.storeList.length == 0) {
					uni.showToast({
						title: '暂无门店',
						icon: "none",
						duration: 1500,
					})
					return
				}
				await this.totalDataInit(bool);
				this.getReward();
			},
			async totalDataInit(bool = false) {
				let totalData,
					plugState = {},
					isMerchantDiy = false;
				try {
					if (bool) {
						({
							totalData,
							plugState,
							isMerchantDiy,
						} = this.oldDiyData);
					} else {
						({
							totalData,
							plugState,
							isMerchantDiy,
						} = this.$root.oldDiyData);
					}

					totalData = JSON.parse(totalData);
					if (totalData.components) {
						let arr = [];
						let len = totalData.components.length - 1;
						for (let i = len; i >= 0; i--) {
							if (totalData.components[i].sign == 'diy-home-top') {
								this.homeTopData = totalData.components[i];
							}
							if (totalData.components[i].sign == 'diy-service') {
								arr.unshift(totalData.components[i]);
								totalData.components.splice(i, 1);
							}
						}
						this.diyServiceList = arr;
					} else {
						this.homeTopData = {
							sign: 'diy-home-top',
							data: {
								backgroundColor: "#333",
								iconMapColor: '#FFF',
								storeSwitchColor: '#FFF',
								searchPlaceholderColor: '#CCC',
								searchBackgroundColor: '#FFF',
								QRCodeColor: '#FFF',
								memberCardColor: '#FFF'
							}
						}
					}

					this.plugState = plugState;
					this.isMerchantDiy = isMerchantDiy;
				} catch (e) {
					this.diyServiceList = [];
					totalData = {
						page: {
							title: "",
							backgroundColor: "#f6f6f6",
							topBackgroundColor: "#333",
							topForeground: 1
						},
						components: [{
							sign: 'diy-home-top',
							data: {
								backgroundColor: "#333",
								iconMapColor: '#FFF',
								storeSwitchColor: '#FFF',
								searchPlaceholderColor: '#CCC',
								searchBackgroundColor: '#FFF',
								QRCodeColor: '#FFF',
								memberCardColor: '#FFF'
							}
						}]
					} // 没有获取到数据时展示的内容
				}

				for (let index = totalData.components.length - 1; index >= 0; index--) {
					if (totalData.components[index].sign != 'diy-drag-area') {
						totalData.components[index].data.isMerchant = this.isMerchantDiy
					}
					if (totalData.components[index].sign == 'diy-seckill' && plugState['seckill_state'] == 0) {
						totalData.components.splice(index, 1);
					} else if (totalData.components[index].sign == 'diy-group-buy' && plugState['group_state'] == 0) {
						totalData.components.splice(index, 1);
					} else if (totalData.components[index].sign == 'diy-pre-sale' && plugState['advance_state'] == 0) {
						totalData.components.splice(index, 1);
					} else if (totalData.components[index].sign == 'diy-gift-card' && plugState['gift_state'] == 0) {
						totalData.components.splice(index, 1);
					} else if (totalData.components[index].sign == 'diy-promotion' && plugState['promotion_state'] ==
						0) {
						totalData.components.splice(index, 1);
					}
				}

				// #ifdef MP-WEIXIN
				if(this.diyServiceList.length){
					const serveice = await this.getService();
					for (let i = 0; i < this.diyServiceList.length; i++) {
						Object.assign(this.diyServiceList[i].data, serveice);
					}
				}
				
				// #endif

				this.totalData = totalData;
				//设置状态栏颜色
				// uni.setNavigationBarColor({
				// 	// #ifdef MP-WEIXIN
				// 	frontColor: totalData.page.topForeground == 1 ? '#ffffff' : '#000000',
				// 	// #endif
				// 	backgroundColor: totalData.page.topForeground == 2 ? '#ffffff' : '#000000',
				// })
			},
			// #ifdef MP-WEIXIN
			async getServicePermissions() {
				const res = await this.$request('SmallProgramApi/My/getServiceOpenid');
				if (res.status == 1) {
					this.service_status = res.data.service_status
					this.ordinary_status = res.data.ordinary_status
				}
			},
			// #endif
			//查找红包
			async getReward() {
				this.open = false; // 红包没有被打开
				this.rotate = false;
				const user = uni.getStorageSync('userInfo');

				const res = await this.$request('SmallProgramApi/Reward/getHomeReward', {
					vid: user.vid ? user.vid : 0,
				})
				if (res.status == 1) {
					this.reward = true;
					this.isVip = user.vid ? 1 : 0; // 是否激活会员卡
				}
			},
			//拆红包
			async toOpen() {
				if (!this.rotate) {
					if (this.isVip != 1) {
						uni.showModal({
							title: '温馨提示',
							content: '您没有激活会员卡，去激活会员领取红包吧！',
							showCancel: true,
							cancelText: '狠心放弃',
							confirmText: '去激活',
							success: (re) => {
								if (re.confirm) {
									uni.navigateTo({
										url: '/pages/mine/card/card'
									})
								}
							}
						})
						return;
					}
					this.rotate = true;
					const res = await this.$request('SmallProgramApi/Reward/openHomeReward');
					if (res.status == 1) {
						this.money = res.money;
						this.open = true;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1500
						})
						this.closeReward();
					}
				}
			},
			//关闭拆红包
			closeReward() {
				this.reward = false;
			},
			async getService() {
				return new Promise(async resolve => {
					const res = await this.$request('SmallProgramApi/BaseSet/getHomeData_v1');
					console.log('getService res', res)
					if (res.status == 1) {
						const data = res;
						let service = {
							customer_service: data.customer_service,
							phone: data.phone,
							supportImg: data.icon.home_support_icon ? data.icon.home_support_icon : '/static/images/icon-support.png',
							telImg: data.icon.home_tel_icon ? data.icon.home_tel_icon : '/static/images/icon-tel.png'
						};
						this.user_type = res.user_type
						resolve(service);
						console.log('getService service', service)
					} else {
						resolve({});
					}
				});
			},
			async getStore() {
				return new Promise(async (resolve, reject) => {
					this.storeList = this.$root.storeList;
					this.store_id = this.$root.store_id;
					this.store_name = this.$root.storeName;
					this.store_switch = this.$root.store_switch
					// #ifdef MP-ALIPAY
					this.cityCode = this.$root.cityCode;
					// #endif
					resolve(true);
				});
			},
			//添加到购物车
			async toAddToCar(data) {
				data.fixed_num = this.sku.canChangeCarNum == 1 ? 0 : 1; //是否不可修改数量
				data.type = 1;
				data.goods_type = 2;
				data.store_id = this.store_id;

				const res = await this.$mutations.setShoppingCar(data);

				if (res) {
					this.sku.canChangeCarNum = 1;
					this.sku.canChangeAddNum = true;
					this.showSelectSku = false;
				}
			},
			//取消选择规格
			closeSku() {
				this.showSelectSku = false;
			},
			//获取SKU
			async getSku(goods) {
				if (goods.attribute_state == 2) {
					this.sku.canChangeAddNum = 1;
					this.sku.canChangeCarNum = 1;
					this.goods = goods;
					this.$nextTick(() => {
						this.showSelectSku = true;
					})
				} else {
					const res = await this.$mutations.setShoppingCar({
						goods_id: goods.goods_id,
						num: 1,
						goods_type: 2
					});
					if (res) {
						this.showSelectSku = false;
					}
				}
			},
		},
	}
</script>
<style lang="less">
	.page_old_diy.home {
		width: 100%;
		height: 100vh;
		background-color: #f6f6f6;

		.old-diy-content {
			overflow-y: scroll;
		}

		.home-empty-goods {
			margin-top: -40rpx;
		}

		/* 红包样式 */
		.draggable-box {
			min-height: 1000px;
		}

		.container {
			width: 100vw;
			height: 100vh;
			display: flex;
			align-items: center;
			justify-content: center;
			position: fixed;
			top: 0;
			left: 0;
			background-color: rgba(0, 0, 0, 0.6);
			z-index: 1;

			.box {
				width: 670rpx;
				height: 768rpx;
				position: relative;
				margin: 0 auto 70px;
				background-color: transparent;
			}
		}

		.reward-bg {
			width: 100%;
			height: 100%;
			border-radius: 2vw;
			position: absolute;
			top: 0;
			left: 0;
		}

		.reward-open {
			width: 200rpx;
			height: 200rpx;
			top: 204rpx;
			left: 236rpx;
			border-radius: 50%;
			position: absolute;
			transition: 1.5s;
			font-size: 0;
		}

		.reward-open>image {
			width: 100%;
			height: 100%;
		}

		.reward-rotate {
			transform: rotateY(360deg);
		}

		.reward-title {
			font-size: 28rpx;
			text-align: center;
			position: relative;
			margin-top: 6vw;
		}

		.reward-money {
			position: absolute;
			bottom: 210rpx;
			left: 0;
			width: 100%;
			text-align: center;
			color: #fdcf9e;
		}


		.reward-money>text:nth-child(1) {
			font-size: 32rpx;
		}

		.reward-money>text:nth-child(2) {
			font-size: 68rpx;
		}

		.reward-tip {
			text-align: center;
			position: absolute;
			bottom: 118rpx;
			left: 0;
			width: 100%;
			color: #fdcf9e;
			font-size: 32rpx;
		}

		.reward-close {
			width: 100%;
			position: absolute;
			left: 0;
			bottom: -15vw;
			display: flex;
			justify-content: center;
		}

		::-webkit-scrollbar {
			width: 0;
			height: 0;
			color: transparent;
			display: none;
		}
	}
</style>
